package com.Downloaders;


import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.view.View;
import android.widget.ProgressBar;
import com.Managers.DirManagerClass;
import com.Managers.PictureManagerClass;


public class PostPictureDownloader extends AsyncTask<String, Integer, Bitmap> {

    private final ProgressBar progress;

    private onDownloadPictureCompleted callbackDownloadPicture;

    public PostPictureDownloader(ProgressBar progress) {

        super();
        this.progress = progress;

    }

    public onDownloadPictureCompleted getCallbackDownloadPicture() {

        return callbackDownloadPicture;
    }

    public void setCallbackDownloadPicture(onDownloadPictureCompleted callbackDownloadPicture) {

        this.callbackDownloadPicture = callbackDownloadPicture;
    }

    private Boolean verifyForFile(String url, String path) {

        File mbmp = new File(path);

        return mbmp.exists();

    }

    private String makePath(String iTag) {

        String fullSdPath = "";
        String withOutExt = "";
        //
        String[] sp = iTag.split("/");
        withOutExt = sp[sp.length - 1];

        // if (downloadProfile) {
        // fullSdPath = Util.SDPATH + Util.PROPATH + withOutExt;
        // }
        // else {
        fullSdPath = DirManagerClass.MainPath + DirManagerClass.ThumbsPath + withOutExt;
        // }

        return fullSdPath;
    }

    private Bitmap downloadImage(String URL, String SDPATH) {

        InputStream input = null;
        OutputStream output = null;
        //
        try {
            //
            URL url = new URL(URL);
            URLConnection conexion = url.openConnection();
            conexion.connect();

            int lenghtOfFile = conexion.getContentLength();

            input = url.openStream();

            output = new FileOutputStream(new File(SDPATH));

            byte[] buffer = new byte[1024];
            int bytesRead = 0;
            //
            int total = 0;
            //
            while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
                total += bytesRead;
                publishProgress(((total * 100)) / lenghtOfFile);
                //
                output.write(buffer, 0, bytesRead);
                //
            }

            Bitmap bmp = PictureManagerClass.ImageResize(BitmapFactory.decodeFile(SDPATH));
            new File(SDPATH).delete();
            bmp.compress(CompressFormat.JPEG, 100, new FileOutputStream(new File(SDPATH)));

            return BitmapFactory.decodeFile(SDPATH);

        }
        catch (Exception x) {
            return null;
        }
        finally {
            try {
                output.close();
            }
            catch (Exception e) {
                downloadImage(URL, SDPATH);
            }
        }
    }

    @Override
    protected Bitmap doInBackground(String... param) {

        String url = param[0];
        String path = makePath(url);

        if (verifyForFile(url, path))
            return BitmapFactory.decodeFile(path);
        else
            return downloadImage(url, path);

    }

    @Override
    protected void onProgressUpdate(Integer... values) {

        if (progress != null) {
            progress.setVisibility(View.VISIBLE);
            //
            progress.setProgress(values[0]);
            //
            if (values[0] == progress.getMax()) {
                progress.setVisibility(View.GONE);
            }
        }
    }

    @Override
    protected void onPostExecute(Bitmap result) {

        if (callbackDownloadPicture != null)
            callbackDownloadPicture.Completed(result);
    }

    public interface onDownloadPictureCompleted {

        void Completed(Bitmap result);
    }
}
